import 'dart:convert';
import 'dart:ffi';
import 'dart:math';

import 'package:crypto/crypto.dart';
import 'package:sonora/models/sj_broad_caster_data.dart';
import 'package:sonora/models/sj_media_data.dart';
import 'package:sonora/models/sj_media_search_item_data.dart';
import 'package:sonora/models/sj_works_model.dart';
import 'package:sonora/utils/sj_storage_utils.dart';

class SjUtils {
  static List<T>? getRandomElements<T>(List<T>? array, int num) {
    if (array == null) return null;
    if (num >= array.length) return array;
    Random random = Random();
    Set<int> indices = {};
    while (indices.length < num) {
      indices.add(random.nextInt(array.length));
    }
    return indices.map((index) => array[index]).toList();
  }

  static String recommendNickname(String? nickname) {
    if (nickname == null) return '';
    if (nickname.length <= 6) return nickname;
    return '${nickname.substring(0, 6)}...';
  }

  static int getRandomNumber() {
    Random random = Random();
    // 生成一个5到20之间的随机整数
    return 5 +
        random.nextInt(16); // nextInt(16) 生成的是 0 到 15 的随机整数，加上 5 后即为 5 到 20
  }

  static List<SjWorksModel>? mockWorksMatchCaster(
      List<SjBroadCasterData>? casterList) {
    List<String> author = [
      'A',
      'B',
      'C',
      'D',
      'E',
      'F',
      'G',
      'H',
      'I',
      'J',
      'K',
      'L'
    ];
    List<SjBroadCasterData>? randomCasters =
        getRandomElements(casterList, author.length);
    if (randomCasters == null) return null;
    SjWorksModel m1 = SjWorksModel(
        author: 'A',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🌿 Handpan vibes for a peaceful day',
        des:
            'Let the handpan melodies carry you to a place of calm and tranquility #HandpanVibes',
        cover: 'assets/images/img_a_1_cover.jpg',
        works: ['assets/images/img_a_1_works.jpg']);

    SjWorksModel m2 = SjWorksModel(
        author: 'A',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🎶 Create harmony with your handpan',
        des:
            'Find balance and creativity with each note you play on the handpan #CreateHarmony',
        cover: 'assets/images/img_a_2_cover.jpg',
        works: ['assets/images/img_a_2_works.jpg']);

    SjWorksModel m3 = SjWorksModel(
        author: 'B',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '✨ Mesmerizing sounds of the handpan',
        des:
            'Dive into a world of enchanting handpan sounds that captivate the soul #MesmerizingHandpan',
        cover: 'assets/images/img_b_1_cover.jpeg',
        works: [
          'assets/images/img_b_1_works.jpeg',
          'assets/images/img_b_1_works_1.jpeg'
        ]);

    SjWorksModel m4 = SjWorksModel(
        author: 'C',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🌟 Unlock your creativity with handpan',
        des:
            'Explore the endless musical possibilities that the handpan offers #UnlockCreativity',
        cover: 'assets/images/img_c_1_cover.jpeg',
        works: ['assets/images/img_c_1_works.jpeg']);

    SjWorksModel m5 = SjWorksModel(
        author: 'C',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🌍 Discover the art of handpan music',
        des:
            'Uncover the beauty and artistry behind playing the handpan #ArtOfHandpan',
        cover: 'assets/images/img_c_2_cover.jpeg',
        works: ['assets/images/img_c_2_works.jpeg']);

    SjWorksModel m6 = SjWorksModel(
        author: 'D',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🎼 Handpan: my musical escape',
        des:
            'Find your escape in the calming and melodic sounds of the handpan #MusicalEscape',
        cover: 'assets/images/img_d_1_cover.jpg',
        works: ['assets/images/img_d_1_works.jpg']);

    SjWorksModel m7 = SjWorksModel(
        author: 'E',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🌈 Handpan rhythms to soothe the soul',
        des:
            'Feel the stress melt away with the soothing rhythms of the handpan #SoothingRhythms',
        cover: 'assets/images/img_e_1_cover.jpg',
        works: ['assets/images/img_e_1_works.jpg']);

    SjWorksModel m8 = SjWorksModel(
        author: 'E',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🌸 Tranquil tunes from my handpan',
        des:
            'Soothe your mind and spirit with the peaceful tunes of the handpan #TranquilTunes',
        cover: 'assets/images/img_e_2_cover.jpeg',
        works: ['assets/images/img_e_2_works.jpeg']);

    SjWorksModel m9 = SjWorksModel(
        author: 'F',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🎵 Journey into handpan melodies',
        des:
            'Embark on a musical adventure with the unique sounds of the handpan #HandpanJourney',
        cover: 'assets/images/img_f_1_cover.jpg',
        works: ['assets/images/img_f_1_works.jpg']);

    SjWorksModel m10 = SjWorksModel(
        author: 'F',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        title: '🎹 Captivating handpan moments',
        des:
            'Cherish the magical moments created by the captivating handpan #CaptivatingMoments',
        cover: 'assets/images/img_f_2_cover.jpg',
        works: [
          'assets/images/img_f_2_works.jpg',
          'assets/images/img_f_2_works_1.jpg'
        ]);

    SjWorksModel m11 = SjWorksModel(
        author: 'G',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🍃 Handpan: the sound of serenity',
        des:
            'Embrace the serene and harmonious sounds of the handpan #SoundOfSerenity',
        cover: 'assets/images/img_g_1_cover.jpg',
        works: ['assets/images/img_g_1_works.jpg']);

    SjWorksModel m12 = SjWorksModel(
        author: 'H',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🎧 Melodies that touch the heart',
        des:
            'Let the touching melodies of the handpan bring peace to your heart #TouchingMelodies',
        cover: 'assets/images/img_h_1_cover.jpg',
        works: ['assets/images/img_h_1_works.jpg']);

    SjWorksModel m13 = SjWorksModel(
        author: 'I',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🌀 Handpan harmony in my hands',
        des:
            'Experience the joy of creating harmony with your handpan #HandpanHarmony',
        cover: 'assets/images/img_i_1_cover.jpeg',
        works: ['assets/images/img_i_1_works.jpeg']);

    SjWorksModel m14 = SjWorksModel(
        author: 'J',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🌌 Elevate your mood with handpan',
        des:
            'Lift your spirits with the uplifting sounds of the handpan #ElevateYourMood',
        cover: 'assets/images/img_j_1_cover.jpeg',
        works: ['assets/images/img_j_1_works.jpeg']);

    SjWorksModel m15 = SjWorksModel(
        author: 'J',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🎨 Handpan: my melodic adventure',
        des:
            'Dive into a melodic adventure with every handpan session #MelodicAdventure',
        cover: 'assets/images/img_j_2_cover.jpg',
        works: ['assets/images/img_j_2_works.jpg']);

    SjWorksModel m16 = SjWorksModel(
        author: 'K',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🍂 Embrace calm with handpan tunes',
        des:
            'Allow the calming tunes of the handpan to bring you peace #CalmTunes',
        cover: 'assets/images/img_k_1_cover.jpeg',
        works: ['assets/images/img_k_1_works.jpg']);

    SjWorksModel m17 = SjWorksModel(
        author: 'L',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🌿 Handpan sounds for inner peace',
        des:
            'Achieve inner peace through the gentle sounds of the handpan #InnerPeace',
        cover: 'assets/images/img_l_1_cover.jpeg',
        works: ['assets/images/img_l_1_works.jpeg']);

    SjWorksModel m18 = SjWorksModel(
        author: 'L',
        worksId: generateTimeBasedId(),
        liked: getRandomNumber(),
        followed: getRandomNumber(),
        title: '🥁 Find your zen with the handpan',
        des:
            'Reach a state of zen with the meditative sounds of the handpan #FindYourZen',
        cover: 'assets/images/img_l_2_cover.jpeg',
        works: [
          'assets/images/img_l_2_works.jpg',
          'assets/images/img_l_2_works_1.jpeg'
        ]);
    List<SjWorksModel> works = [
      m1,
      m2,
      m3,
      m4,
      m5,
      m6,
      m7,
      m8,
      m9,
      m10,
      m11,
      m12,
      m13,
      m14,
      m15,
      m16,
      m17,
      m18
    ];
    List<SjWorksModel> resultWorks = [];
    var index = 0;
    for (var au in author) {
      for (var w in works) {
        if (w.author == au && randomCasters.length > index) {
          resultWorks.add(w.copyWith(
              isLiked: false,
              userId: randomCasters[index].userId,
              nickname: randomCasters[index].nickname,
              avatar: randomCasters[index].avatar));
        }
      }
      if (index <= randomCasters.length) {
        index++;
      }
    }
    return resultWorks;
  }

  static List<SjMediaSearchItemData> mediaSearchParamsList() {
    List<String> mediaName = [
      'aface/lanlin/Sonora/video/1.mp4',
      'aface/lanlin/Sonora/video/2.mp4',
      'aface/lanlin/Sonora/video/3.mp4',
      'aface/lanlin/Sonora/video/4.mp4',
      'aface/lanlin/Sonora/video/5.mp4',
      'aface/lanlin/Sonora/video/6.mp4',
      'aface/lanlin/Sonora/video/7.mp4',
      'aface/lanlin/Sonora/video/8.mp4',
      'aface/lanlin/Sonora/video/9.mp4',
      'aface/lanlin/Sonora/video/10.mp4',
      'aface/lanlin/Sonora/video/11.mp4',
      'aface/lanlin/Sonora/video/12.mp4',
    ];
    List<SjMediaSearchItemData> list = mediaName
        .map((e) => SjMediaSearchItemData(mediaPath: e, mediaType: 'video'))
        .toList();
    return list;
  }

  static Future<List<SjMediaData>?> dealMediaSearchList(
      List<dynamic> list) async {
    List<SjMediaData> mediaList =
        list.map((e) => SjMediaData.fromJson(e)).toList();
    List<SjBroadCasterData>? broadCasters =
        await SjStorageUtils.getWallSearchList();
    List<SjBroadCasterData>? matchList =
        getRandomElements(broadCasters, mediaList.length);
    List<String> mediaTitle = [
      '🎶 Discover the magic of handpan music Feel the rhythm',
      '✨ Create your own melody with the enchanting handpan',
      '🌿 Let the soothing sounds of the handpan relax your mind',
      '🎵 Unlock the secrets of handpan playing and elevate your skills',
      '🌌 Experience tranquility through the harmonious notes of a handpan',
      '🎼 Learn how to play a handpan like a pro with these simple tips',
      '🌍 Dive into the world of handpan music and explore new sounds',
      '🍃 Transform your day with the calming tones of the handpan',
      '🌟 Find your inner peace with the mesmerizing handpan melodies',
      ' 🎨 Explore the art of handpan and create beautiful music',
      ' 🛤️ The handpan journey begins here Start your musical adventure',
      ' 🥁 Master the handpan and impress your friends with your talent',
    ];
    List<SjMediaData> result = [];
    if (matchList != null && matchList.isNotEmpty) {
      int index = 0;
      while (index < mediaList.length &&
          index < matchList.length &&
          index < mediaTitle.length) {
        result.add(mediaList[index].copyWith(
            mediaId: generateTimeBasedId(),
            broadCaster: matchList[index],
            title: mediaTitle[index],
            assetPath: 'assets/video/${index + 1}.mp4'));
        index++;
      }
      if (result.isNotEmpty) {
        SjStorageUtils.saveMedialList(result);
        return result;
      }
    }
    return null;
  }

  static String? strMD5(String? text) {
    if (text == null) return null;
    List<int> bytes = utf8.encode(text);
    Digest md5Digest = md5.convert(bytes);
    String md5Hash = md5Digest.toString();
    return md5Hash;
  }

  static String generateTimeBasedId() {
    final now = DateTime.now();
    final timestamp = now.toIso8601String();
    final random = Random().nextInt(10000);
    return '$timestamp$random';
  }
}
